import React, { useRef, useState } from "react";
import add from "../../assets/images/add1.webp";
import "./style.css";
import { message } from "antd";
import axios from "axios";
const Index = () => {
  const input = useRef<HTMLInputElement | null>(null);
  const [url, setUrl] = useState("");

  const onClick = () => {
    if (input.current) input.current.click();
  };

  const onChange = async () => {
    if (input.current) {
      // 获取上传的文件列表
      const files = input.current.files;
      if (files) {
        // 获取上传的文件
        const file = files[0];
        // 1. 创建formData 对象
        const formData = new FormData();
        // 2. 将文件放入 formData 数据里面
        formData.append("chunk", file, file.name);

        // 3. 发送数据
        const resp = await axios.post("/api/upload/avator", formData);
        
        setUrl(resp.data.data.url);
      }
    }
  };

  return (
    <div>
      <div className="upload" onClick={() => onClick()}>
        <img src={url || add} alt="" className="upload-avator" />
        <input
          ref={input}
          type="file"
          style={{ display: "none" }}
          onChange={() => onChange()}
        />
      </div>
    </div>
  );
};

export default Index;
